'use strict'

const Controller = require('egg').Controller
const FenceModel = require('../../models/main_fence_table')
const FenceSubModel = require('../../models/fence_sub_table')
const UserBoundDeviceModel = require('../../models/user_bound_device')
const dayjs = require('dayjs')
const { Op } = require('sequelize')

class FenceController extends Controller {
  fenceModel = FenceModel(this.app.model)

  fenceSubModel = FenceSubModel(this.app.model)

  userBoundDeviceModel = UserBoundDeviceModel(this.app.model)

  async create() {
    const { ctx, app } = this
    const { name, equipmentId: equipment_id, postion } = ctx.request.body
    if (!name || !equipment_id) {
      return ctx.failure('参数非法')
    }
    if (!postion.length || !Array.isArray(postion)) {
      return ctx.failure('postion字段非法')
    }
    const transaction = await app.model.transaction() // 启用事务
    const id = ctx.helper.generateId()
    try {
      await this.fenceModel.create(
        {
          name,
          equipment_id,
          id,
          type: 0,
          del_flag: '0',
        },
        { transaction }
      )
      await Promise.all(
        postion.map(async item => {
          const { longitude, dimension } = item
          let param = {
            id: ctx.helper.generateId(),
            main_id: id,
            longitude,
            dimension,
            del_flag: '0',
          }
          return await this.fenceSubModel.create(param, {
            transaction,
          })
        })
      )
      await transaction.commit()
      return ctx.success('插入成功')
    } catch (error) {
      await transaction.rollback() // 回滚事务
      return ctx.failure('系统异常', error)
    }
  }

  async queryById() {
    const { ctx } = this
    const { id } = ctx.query
    try {
      const feceMainresult = await this.fenceModel.findOne({
        where: { del_flag: '0', id },
      })
      const subResult = await this.fenceSubModel.findAll({
        where: {
          main_id: feceMainresult?.dataValues?.id,
        },
      })
      feceMainresult.dataValues.subModel = subResult
      ctx.success('成功', feceMainresult)
    } catch (error) {
      return ctx.failure('系统异常', error)
    }
  }

  async query() {
    const { ctx } = this
    try {
      const deviceResult = await this.userBoundDeviceModel.findAll({
        where: { user_id: ctx.userId },
      })
      if (!deviceResult?.length) {
        return ctx.success('deviceResult无数据', deviceResult)
      }
      const equipmentList = deviceResult?.map(item => {
        return item.equipment_id
      })
      const result = await this.fenceModel.findAll({
        where: {
          del_flag: '0',
          equipment_id: {
            [Op.in]: equipmentList,
          },
        },
      })
      return ctx.success('成功', result)
    } catch (error) {
      return ctx.failure('系统异常', error)
    }
  }

  async update() {
    const { ctx } = this
    const { id } = ctx.query
    const where = { id }
    try {
      const result = await this.fenceModel.update({ del_flag: 1 }, { where })
      ctx.success(result ? '更新成功' : '未查询到数据', result)
    } catch (error) {
      ctx.failure('系统异常', error)
    }
  }
}

module.exports = FenceController
